
from apps.chat.conversation.dao import ConversationDao
from apps.chat.message.dao import MessageDao

class MessageFun:

    def sendMessage(self, befromUser, toUser, messageType, params):
        try:
            befromUser_id = befromUser.id if befromUser else ''
            messageType = messageType or 'system'
            contentType = params.get('contentType') or 'text'
            message = None
            conversation = None
            # 首先创建一条消息
            data = {"befrom": befromUser_id, "to": toUser.id, "title": params.get('title'), "content": params.get('content'), "contentType": contentType,
                    "messageType": messageType}
            message = MessageDao().create(data)
            # 首先查找双方是否有会话
            conversationList1 = ConversationDao().findAll().filter(userA=befromUser, userB=toUser, conversationType=messageType)
            conversationList2 = ConversationDao().findAll().filter(userA=toUser, userB=befromUser, conversationType=messageType)
            conversation = None
            if conversationList1.exists() > 0:
                conversation = conversationList1.first()
                conversation.lastMessage = message
                conversation.save()
            elif conversationList2.exists() > 0:
                conversation = conversationList2.first()
                conversation.lastMessage = message
                conversation.save()
            else:
                conversation = ConversationDao().create(
                    {"userA": befromUser_id, "userB": toUser.id, "lastMessage": message.id, "conversationType": messageType})

            # 关联该消息的会话ID
            message.conversation = conversation
            message.save()
            return {"conversationId": conversation.id, "messageId": message.id}
        except Exception as e:
            print('发送消息异常', e)
            return {"message": '发送异常'}
